<template>
    <el-row :gutter="20">
        <el-col :span="4">
            <el-input v-model="searchName" placeholder="查询商品信息..." @input="searchByName" />
        </el-col>
        <el-col :span="3">
            <el-button type="success" @click="dialogTableVisible = true">添加商品</el-button>
        </el-col>
    </el-row>

    <!-- 新增商品的对话框 -->
    <el-dialog v-model="dialogTableVisible">
        <el-form label-position="right" label-width="100px">
            <el-form-item label="品名">
                <el-input v-model="uploadGoods.name" />
            </el-form-item>
            <el-form-item label="封面图">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="coverInfo">
                    <img v-if="uploadGoods.cover" :src="api.imgUrl + uploadGoods.cover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="介绍图A">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="image1Info">
                    <img v-if="uploadGoods.image1" :src="api.imgUrl + uploadGoods.image1" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="介绍图B">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="image2Info">
                    <img v-if="uploadGoods.image2" :src="api.imgUrl + uploadGoods.image2" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="价格">
                <el-input v-model="uploadGoods.price" />
            </el-form-item>
            <el-form-item label="介绍文字">
                <el-input type="textarea" v-model="uploadGoods.intro" />
            </el-form-item>
            <el-form-item label="分类">
                <el-radio-group v-model="uploadGoods.typeId">
                    <el-radio v-for="(types, index) in typelist" :key="index" :label="types.id" name="typelist">
                        {{ types.name }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-button type="success" @click="addGoods">上传</el-button>
        </el-form>
    </el-dialog>

    <!-- 修改商品的对话框 -->
    <el-dialog v-model="dialogTableVisible2">
        <el-form label-position="right" label-width="100px">
            <el-form-item label="品名">
                <el-input v-model="updateGoods.name" />
            </el-form-item>
            <el-form-item label="封面图">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="coverInfo">
                    <img v-if="updateGoods.cover" :src="api.imgUrl + updateGoods.cover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="介绍图A">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="image1Info">
                    <img v-if="updateGoods.image1" :src="api.imgUrl + updateGoods.image1" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="介绍图B">
                <el-upload class="avatar-uploader" :action="api.imgUrl + '/files/'" :show-file-list="false" name="file"
                    :on-success="image2Info">
                    <img v-if="updateGoods.image2" :src="api.imgUrl + updateGoods.image2" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="价格">
                <el-input v-model="updateGoods.price" />
            </el-form-item>
            <el-form-item label="介绍文字">
                <el-input type="textarea" v-model="updateGoods.intro" />
            </el-form-item>
            <el-form-item label="分类">
                <el-radio-group v-model="updateGoods.typeId">
                    <el-radio v-for="(types, index) in typelist" :key="index" :label="types.id" name="typelist">
                        {{ types.name }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-button type="success" @click="updateInfo">上传</el-button>
        </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table :data="tableData()" height="500" style="width: 100%;">
        <el-table-column type="index" />
        <el-table-column prop="id" label="商品id" width="100px" />
        <el-table-column label="封面图" width="200px">
            <template #default="scope">
                <el-popover placement="auto" :width="400" trigger="hover">
                    <template #reference>
                        <img :src="api.imgUrl + scope.row.cover" class="imgWid" />
                    </template>
                    <img :src="api.imgUrl + scope.row.cover" class="imgWid2" />
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column label="介绍图A" width="200px">
            <template #default="scope">
                <el-popover placement="auto" :width="400" trigger="hover">
                    <template #reference>
                        <img :src="api.imgUrl + scope.row.image1" class="imgWid" />
                    </template>
                    <img :src="api.imgUrl + scope.row.image1" class="imgWid2" />
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column label="介绍图B" width="200px">
            <template #default="scope">
                <el-popover placement="auto" :width="400" trigger="hover">
                    <template #reference>
                        <img :src="api.imgUrl + scope.row.image2" class="imgWid" />
                    </template>
                    <img :src="api.imgUrl + scope.row.image2" class="imgWid2" />
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="品名" />
        <el-table-column prop="price" label="价格" />
        <el-table-column label="简介">
            <template #default="scope">
                <el-popover placement="auto" :width="400" trigger="hover">
                    <template #reference>
                        <p>
                            {{ scope.row.intro.substring(0, 10) + '...' }}
                        </p>
                    </template>
                    <p> {{ scope.row.intro }} </p>
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
            <template #default="scope">
                <el-button type="danger" :icon="Delete" @click="removeInfo(scope.row.id)" />
                <el-button type="success" :icon="Edit" @click="beforeUpdateInfo(scope.row)" />
            </template>
        </el-table-column>
    </el-table>
    <div class="example-pagination-block">
        <el-pagination background layout="prev, pager, next, total, sizes" :total="state.total"
            @current-change="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
</template>

<script setup>
import api from '@/api/api';
import { onMounted, ref } from 'vue';
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, uploadProps } from 'element-plus'

var info = ref([]);
var searchName = ref('');
var dialogTableVisible = ref(false);
var dialogTableVisible2 = ref(false);

const typelist = ref({})
var uploadGoods = ref({
    name: '',
    cover: '',
    image1: '',
    image2: '',
    price: 0,
    intro: '',
    typeId: 1,
})
var updateGoods = ref({
    name: '',
    cover: '',
    image1: '',
    image2: '',
    price: 0,
    intro: '',
    typeId: 1,
});

// 文件上传成功后的处理（自动上传）
const coverInfo = (response, uploadFile) => {
    uploadGoods.value.cover = response.result;
    return;
}
const image1Info = (response, uploadFile) => {
    uploadGoods.value.image1 = response.result;
    return;
}
const image2Info = (response, uploadFile) => {
    uploadGoods.value.image2 = response.result;
    return;
}

// 分页 https://blog.csdn.net/Xwf1023/article/details/126956007
const state = ref({
    page: 1,
    limit: 10,
    total: info.value.length,
});

//前端限制分页（tableData为当前展示页表格）
const tableData = () => {
    return info.value.filter(
        (item, index) =>
            index < state.value.page * state.value.limit &&
            index >= state.value.limit * (state.value.page - 1)
    );
};
//改变页码
const handleCurrentChange = (e) => {
    state.value.page = e;
};
//改变页数限制
const handleSizeChange = (e) => {
    state.value.limit = e;
};
// -----------------------

// 删除商品
const removeInfo = (id) => {
    ElMessageBox.confirm(
        '确认删除商品？这将无法恢复！',
        "提示！",
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
        }
    ).then(() => {
        api.removeGoods(id)
            .then(ret => {
                if (ret.flag) {
                    ElMessage({
                        message: '删除完成',
                        type: 'success'
                    })
                    goodsInfo.apply();
                    return;
                }
                else {
                    ElMessage({
                        message: '删除失败',
                        type: 'error'
                    })
                    return;
                }
            })
    })

}

// 商品信息存储
const addGoods = () => {
    api.addGoods(uploadGoods)
        .then(ret => {
            if (ret) {
                ElMessage({
                    message: '添加成功',
                    type: 'success'
                })
                dialogTableVisible.value = false;
            }
            else {
                ElMessage({
                    message: '添加失败',
                    type: 'error'
                })
            }
        })
}


// 点击更新商品按钮后的操作
const beforeUpdateInfo = (goods) => {
    dialogTableVisible2.value = true;
    updateGoods.value = goods;
}

// 更新商品
const updateInfo = () => {
    api.updateGoods(updateGoods)
        .then(ret => {
            if (ret) {
                ElMessage({
                    message: '更新成功',
                    type: 'success'
                })
                dialogTableVisible2.value = false;
            }
            else {
                ElMessage({
                    message: '更新失败',
                    type: 'error'
                })
            }
        })
}

// 查找商品
const searchByName = () => {
    // 如果值为空，直接查询所有
    if (searchName.value == '') {
        goodsInfo.apply();
        return;
    }
    api.searchGoodsByName(searchName.value)
        .then(ret => {
            info.value = ret.result;
            state.value.total = info.value.length;
        })
}

// 初始化
const goodsInfo = () => {
    api.getAllGoods()
        .then(ret => {
            info.value = ret.result;
            // 由于异步请求原因，需要在此处给分页对象的total赋值，否则获取不到
            state.value.total = info.value.length;
            return;
        })
    api.showTypeList()
        .then(ret => {
            typelist.value = ret.result;
        })
}

onMounted(goodsInfo);

</script>

<style scoped>
.imgWid {
    width: 8%;
}

.imgWid2 {
    width: 100%;
}

/* 图片上传区域样式 */
.avatar-uploader .avatar {
    width: 30px;
    height: 30px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>